package editor.UI
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;
	import game.manager.ConfigurationManager;
	import game.manager.TemplateTileManager;
	import game.VO.TileTemplateVO;
	import starling.core.Starling;
	import starling.events.ResizeEvent;
	
	/**
	 * @author Kiril Pletnev
	 */
	public class NewTileWindow extends NewTileWindowUI
	{
		public static const CREATE_TILE_EVENT:String = "createTile";
		public static const CLOSE_WINDOW_EVENT:String = "closeWindow";
		
		public function NewTileWindow()
		{
		}
		
		public function create():void
		{
			Starling.current.stage.addEventListener(ResizeEvent.RESIZE, resizeStage);
			cancelBtn.addEventListener(MouseEvent.CLICK, onCancelBtnClick);
			createBtn.addEventListener(MouseEvent.CLICK, onCreateBtnClick);
			tileImageName.addEventListener(Event.CHANGE, onChangeTileName);
			preview.addEventListener(IOErrorEvent.IO_ERROR, onIoError);
			resizeStage();
			
			info.text = "Path to the texture file must be relative to " + ConfigurationManager.instance.pathToTileRes;
			
			Starling.current.nativeOverlay.addChild(this);
		}
		
		private function onChangeTileName(event:Event):void
		{
			preview.source = ConfigurationManager.instance.pathToTileRes + tileImageName.text;
		}
		
		private function onCancelBtnClick(event:MouseEvent):void
		{
			dispatchEvent(new Event(CLOSE_WINDOW_EVENT));
		}
		
		private function onIoError(event:IOErrorEvent):void
		{
			trace(event);
		}
		
		private function onCreateBtnClick(event:MouseEvent):void
		{
			var tile:TileTemplateVO = new TileTemplateVO();
			tile.textureURL = tileImageName.text;
			tile.walkable = walkable.selected;
			tile.id = TemplateTileManager.DEFAULT_TILE_ID;
			TemplateTileManager.instance.addNewTile(tile);
			
			dispatchEvent(new Event(CREATE_TILE_EVENT));
		}
		
		public function dispose():void
		{
			Starling.current.stage.removeEventListener(ResizeEvent.RESIZE, resizeStage);
			cancelBtn.removeEventListener(MouseEvent.CLICK, onCancelBtnClick);
			createBtn.removeEventListener(MouseEvent.CLICK, onCreateBtnClick);
			tileImageName.removeEventListener(Event.CHANGE, onChangeTileName);
			preview.removeEventListener(IOErrorEvent.IO_ERROR, onIoError);
			preview.unload();
			
			Starling.current.nativeOverlay.removeChild(this);
		}
		
		private function resizeStage(event:ResizeEvent = null):void
		{
			var viewPort:Rectangle = Starling.current.viewPort;
			
			this.x = viewPort.width >> 1;
			this.y = viewPort.height >> 1;
		}
	}
}